package com.hepinghospital.user.ui.fragment;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.base.BaseLoadsirFragment;
import com.hepinghospital.user.eventbus.RefreshEvent;
import com.hepinghospital.user.ui.PayActivity;
import com.hepinghospital.user.ui.activity.consult.ChatActivity;
import com.hepinghospital.user.ui.activity.consult.DiagnoseOrderDetailActivity;
import com.hepinghospital.user.ui.widget.EmptyCallback;
import com.hepinghospital.user.util.CustomViewExtKt;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.observer.BaseObserver;
import com.rest.response.CloudResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.UIConstants;


/**
 * Created by HP on 2020/2/25.
 */

public class PicListFragment extends BaseLoadsirFragment {

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    private String type = "0";
    MyAdapter adapter;
    List<CloudResponse> list = new ArrayList<>();

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_cloud_list;
    }

    @Override
    protected void initView() {
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        adapter = new MyAdapter();
        CustomViewExtKt.init(recyclerView, manager, adapter, true);

        if (recyclerView.getItemDecorationCount() == 0) {
            recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
                @Override
                public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
                    super.onDraw(c, parent, state);
                }

                @Override
                public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                    super.getItemOffsets(outRect, view, parent, state);
                    outRect.bottom = DpUtil.dip2px(mContext, 10);
                }
            });
        }
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshlayout -> getConsultationList(type));
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {

        });

    }

    @Override
    protected void initData() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        type = getArguments().getString("type");
        getConsultationList(type);
    }

    @Override
    protected void onNetReload(View v) {
        getConsultationList(type);
    }

    public static PicListFragment newInstance(String type) {
        Bundle args = new Bundle();
        args.putString("type", type);
        PicListFragment fragment = new PicListFragment();
        fragment.setArguments(args);
        return fragment;
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {
        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(getActivity()).inflate(R.layout.item_my_ask2, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(final Holder holder, final int position) {
            // 0全部  1待支付   3进行中  4待评价  5已取消  7已评价/已结束
            //1->10   3->35  4->40   5->20   7->70  6->已退款
            //10待支付 20已取消 30支付中 35已付款(已支付门诊未结束 表里不会存入) 40待评价(已支付未评价门诊已结束) 50退款中  60已退款 70已评价(已支付已评价门诊已结束)
            int status = list.get(position).orderStatus;
            holder.itemView.setOnClickListener(v -> {
                if (status == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cloudObj", list.get(position));
                    bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_5);
                    startActivity(PayActivity.class, bundle);
                } else if (status == 2) {
                    if (list.get(position).readyFlag == 1) {
                        //已经报道
                        Bundle bundle = new Bundle();
                        bundle.putString("diagnoseId", list.get(position).diagnoseId);
                        startActivity(ChatActivity.class, bundle);
                    }
                } else if (status == 3 || status == 8) {
                    Bundle bundle = new Bundle();
                    bundle.putString("diagnoseId", list.get(position).diagnoseId);
                    startActivity(ChatActivity.class, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putString("diagnoseId", list.get(position).diagnoseId);
                    startActivity(DiagnoseOrderDetailActivity.class, bundle);
                }
            });
            holder.tvDepartment.setText(list.get(position).deptName);

            if (list.get(position).businessType == UIConstants.GRAPHIC_TYPE_1) {
                holder.tvConsultType.setText(R.string.string_consult);
            } else if (list.get(position).businessType == UIConstants.GRAPHIC_TYPE_2) {
                holder.tvConsultType.setText(R.string.string_referral);
            }
            holder.tvStatus.setText(getStatus(list.get(position).orderStatus, list.get(position).readyFlag));
            holder.tvName.setText(list.get(position).doctorName);
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, list.get(position).url, holder.imgHead);
            holder.tv_patient.setText(list.get(position).patientName);
            switch (status) {
                //待支付
                case 1:
                    holder.tvDetail.setVisibility(View.VISIBLE);
                    holder.tvDetailOne.setVisibility(View.VISIBLE);
                    holder.tvDetailTwo.setVisibility(View.VISIBLE);
                    holder.btnConfirm.setVisibility(View.VISIBLE);
                    holder.btnConfirm.setText("立即支付");
                    holder.tv_diagnose.setVisibility(View.GONE);
                    holder.tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.color_F54C4C));
                    //将前一个缓存清除
                    if (holder.timer != null) {
                        holder.timer.cancel();
                    }
                    final int parseInt = Integer.parseInt(list.get(position).remainPayTime);
                    holder.timer = new CountDownTimer(parseInt * 1000, 1000) {
                        @Override
                        public void onTick(long millisUntilFinished) {
                            if (millisUntilFinished / 60000 / 60 != 0) {
                                holder.tvDetail.setText(millisUntilFinished / 60000 / 60 + "时" + millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
                            } else {
                                holder.tvDetail.setText(millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
                            }
//                            holder.tvDetail.setText(millisUntilFinished / 60000 / 60 + "时" + millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
                        }

                        @Override
                        public void onFinish() {
                            //倒计时为0时执行此方法
                            holder.tvDetail.setText("已超时");
                            holder.timer.cancel();
                            holder.tvDetailOne.setVisibility(View.GONE);
                            holder.tvDetailTwo.setVisibility(View.GONE);

                        }
                    };
                    holder.timer.start();
                    break;
                case 3:
                    //进行中
                    holder.tvDetail.setVisibility(View.GONE);
                    holder.tvDetailOne.setVisibility(View.GONE);
                    holder.tvDetailTwo.setVisibility(View.GONE);
                    holder.btnConfirm.setVisibility(View.GONE);
//                    holder.btnConfirm.setText("取消咨询");
                    break;
                case 4:
                    //已结束
                    holder.tvDetail.setVisibility(View.GONE);
                    holder.tvDetailOne.setVisibility(View.VISIBLE);
                    holder.tvDetailTwo.setVisibility(View.GONE);
                    holder.btnConfirm.setVisibility(View.VISIBLE);
                    holder.btnConfirm.setText("立即评价");
                    holder.tv_diagnose.setVisibility(View.VISIBLE);
                    holder.tv_diagnose.setText(list.get(position).diagnoseName);
                    holder.tvDetailOne.setText(list.get(position).endTime);
                    holder.tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.orange));
                    break;
                case 5:
                    //已取消
                    holder.tvDetail.setVisibility(View.GONE);
                    holder.tvDetailOne.setVisibility(View.GONE);
                    holder.tvDetailTwo.setVisibility(View.GONE);
                    holder.btnConfirm.setVisibility(View.GONE);
                    holder.tv_diagnose.setVisibility(View.GONE);
                    holder.tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
                    break;
                default:
                    holder.tvDetail.setVisibility(View.GONE);
                    holder.tvDetailOne.setVisibility(View.GONE);
                    holder.tvDetailTwo.setVisibility(View.GONE);
                    holder.btnConfirm.setVisibility(View.GONE);
                    holder.tv_diagnose.setVisibility(View.GONE);
                    holder.btn_refund.setVisibility(View.GONE);
                    holder.btn_cancel.setVisibility(ViewGroup.GONE);
                    holder.tvStatus.setTextColor(ContextCompat.getColor(mContext, R.color.commonGrey));
                    break;
            }
            holder.btnConfirm.setOnClickListener(v -> {
                if (status == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cloudObj", list.get(position));
                    bundle.putInt(UIConstants.PayActivity_TYPE_FLAG, UIConstants.PayActivity_TYPE_5);
                    startActivity(PayActivity.class, bundle);
                } else if (status == 3) {
                    cancelOrder(list.get(position).orderId);
                } else if (status == 4) {
                    Bundle bundle = new Bundle();
                    bundle.putString("diagnoseId", list.get(position).diagnoseId);
                    startActivity(DiagnoseOrderDetailActivity.class, bundle);
                }
                if (list.get(position).canRefund == 1) {
                    refund(list.get(position).orderNumber);
                }
            });

            holder.btn_cancel.setOnClickListener(v -> cancelOrder(list.get(position).orderId));

            if (list.get(position).canRefund == 1) {
                holder.btn_refund.setVisibility(View.VISIBLE);
            } else {
                holder.btn_refund.setVisibility(View.GONE);
            }
            if (list.get(position).canCancel) {
                holder.btn_cancel.setVisibility(ViewGroup.VISIBLE);
            } else {
                holder.btn_cancel.setVisibility(ViewGroup.GONE);
            }
            holder.btn_refund.setOnClickListener(v -> refund(list.get(position).orderNumber));
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            @BindView(R.id.img_head)
            ImageView imgHead;
            @BindView(R.id.tv_name)
            TextView tvName;
            @BindView(R.id.tv_department)
            TextView tvDepartment;
            @BindView(R.id.tv_consult_type)
            TextView tvConsultType;
            @BindView(R.id.tv_status)
            TextView tvStatus;
            @BindView(R.id.line)
            View line;
            @BindView(R.id.tv_detail_one)
            TextView tvDetailOne;
            @BindView(R.id.tv_detail)
            TextView tvDetail;
            @BindView(R.id.tv_detail_two)
            TextView tvDetailTwo;
            @BindView(R.id.btn_confirm)
            TextView btnConfirm;
            @BindView(R.id.tv_patient)
            TextView tv_patient;
            @BindView(R.id.tv_diagnose)
            TextView tv_diagnose;
            @BindView(R.id.btn_refund)
            TextView btn_refund;
            @BindView(R.id.btn_cancel)
            TextView btn_cancel;

            private CountDownTimer timer;

            Holder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
        }
    }

    private void getConsultationList(String orderStatus) {
        Log.e("orderStatus--------", orderStatus);
        RestProxy.getInstance().getConsultationList(BaseApplication.currentUserId, orderStatus, new BaseObserver<List<CloudResponse>>() {
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                Log.e("onError----------", e.getMessage());
                ToastUtil.onError(mContext, e);
                refreshLayout.finishRefresh(false);
            }


            @Override
            public void onSuccess(List<CloudResponse> result) {
                list.clear();
                list.addAll(result);
                adapter.notifyDataSetChanged();
                refreshLayout.finishRefresh(true);
                if (result.isEmpty()) {
                    mBaseLoadService.showCallback(EmptyCallback.class);
                } else {
                    mBaseLoadService.showSuccess();
                }
            }
        });
    }

    private String getStatus(int status, int readyFlag) {
        switch (status) {
            case 1:
                return "待支付";
            case 2:
                if (readyFlag == 1) {
                    return "已报道";
                } else {
                    return "未报道";
                }
            case 3:
                return "进行中";
            case 4:
                return "待评价";
            case 5:
                return "已取消";
            case 6:
                return "已退款";
            case 7:
                return "已完成";
            case 10:
                return "退款中";
            default:
                return "";
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    @Subscribe
    public void onFresh(RefreshEvent event) {
        getConsultationList(type);
    }

    //    private void createWXOrder(String orderId) {
//        BaseApplication.currentOrderId = orderId;
//        RestProxy.getInstance().createOrder(orderId, fee, "", "", new Observer<PayResponse>() {
//            @Override
//            public void onSubscribe(Disposable d) {
//
//            }
//
//            @Override
//            public void onNext(PayResponse payResponse) {
//                switch (payResponse.getType) {
//                    case 1:
//                        showPayDialog(payResponse);
//                        break;
//                    case 2:
//                        ToastUtil.showToast(mContext, "请到药店自取");
//                        break;
//                    case 3:
//                        ToastUtil.showToast(mContext, "请到医院自取");
//                        finish();
//                        break;
//                    case 4:
//                        Bundle bundle = new Bundle();
//                        bundle.putInt("type", 1);
//                        startActivity(WXPayEntryActivity.class, bundle);
//                        ToastUtil.showToast(mContext, "医保已全额报销");
//                        finish();
//                        break;
//                    default:
//                        break;
//                }
//            }
//
//            @Override
//            public void onError(Throwable e) {
//                ToastUtil.onError(mContext, e);
//                dismissLoadingDialog();
//            }
//
//            @Override
//            public void onComplete() {
//            }
//        });
//    }


    private void cancelOrder(String orderId) {
        RestProxy.getInstance().cancelOrder(orderId, new BaseObserver<String>() {

            @Override
            public void onSuccess(String s) {
                getConsultationList(type);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

        });
    }

    private void refund(String orderNumber) {
        RestProxy.getInstance().refund(orderNumber, new BaseObserver<String>() {

            @Override
            public void onSuccess(String s) {
                getConsultationList(type);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }
        });
    }
}
